<?php
/**
 * Created by PhpStorm.
 * User: pc
 * Date: 2019/1/21
 * Time: 20:18
 */

namespace app\api\controller;

use think\Db;
use \app\api\model\Resource as ResourceModel;
use \app\api\model\Product as ProductModel;

class Product extends Main
{

    public $uid;
    public $username;
    public $truename;
    public $password;
    public $company_id;
    public $type;
    public $lastversion;//上传版本号
//    public $lastversion = "20190307115800";//上传版本号
    public $officeManage = 3;//1总公司总管理员2子公司管理员3员工
    public $maxhostsize = 0;//允许上传文件大小（G）,0不限
    public $currenthostsize = 0;//已使用大小字节（B）,0不限
    public $module = 'product';
    public $ProductModel;
    public $productImg;
    public $path;//图片存储路径
    public $temfile;//临时文件夹
    public $dir;//跟目录
    //颜色数组
    public $colors = array(
        'color',
        'couleur',
        'cor',
        '颜色',
        '색상',
        '顏色',
        'renk',
        'colore',
        'farbe',
        'colour',
        'Цвет',
        'kolor',
        'צבע',
        'اللون'
    );

    public $extensions = array(
        'image/bmp' => 'bmp',
        'image/gif' => 'gif',
        'image/jpeg' => 'jpg',
        'image/png' => 'png',
        'image/x-icon' => 'ico'
    );

    public function _initialize()
    {
        $config = config('database');//数据库配置
        $this->lastversion = $config['apiproductversion'];   //上传版本号
        $this->dir = server('DOCUMENT_ROOT');
        $this->ResourceModel = new ResourceModel();
    }

    /**
     * 用户验证
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function verifyLogin()
    {
        $this->username = get('username');
        $this->password = get('password');
        $res = $this->detectLogin($this->username, $this->password);
        if ($res['state'] == false) {
            $this->returnJson($res['content']);
        }
        $user = $res['content'];

        $this->uid = $user['id'];
        $this->company_id = $user['company_id'];
        $this->type = $user['type'];
        $this->truename = $user['truename'];
        //总公司总管理员
        if (($user['super'] == 2) && ($user['pid'] == 1) && ($user['company_id'] == 0) && ($user['type'] == 1)) {
            $this->officeManage = 1;
        }
        //子管理员
        if (($user['super'] == 3) && ($user['type'] == 2)) {
            $this->officeManage = 2;
        }

        //总空间、已使用空间
        if ($user['company_id'] != 0) {
            $company = DB::name('company')->where('id', $user['company_id'])->find();
            $this->maxhostsize = isset($company['upload_capacity']) ? $company['upload_capacity'] : 0;
            $this->currenthostsize = isset($company['use_capacity']) ? $company['use_capacity'] : 0;
        }
        $this->path = '/files/' . $this->uid . '/product/' . date("Ymd", time()) . '/';
        $this->temfile = '/files/' . $this->uid . '/product/temfile/';
    }

    /*************************************** 上传产品 *********************************************************/

    /**
     * 产品上传
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function upload()
    {
        //用户登录验证
        $this->verifyLogin();

        $data = json_decode(post('data'), true);
        $version = $data['Version'];
        //版本验证
        if ($this->lastversion !== $version) {
            $this->returnJson("UnVersion");
        }
        $action = get('action');
        switch ($action) {
            case 'check'://检测产品是否已经存在
                $this->checkProduct($data);
                break;
            case 'imageurl'://下载远程图片
                $this->uplodaImgUrl($data);
                break;
            case 'imagebase64'://下载本地图片
                $this->uplodaImg($data);
                break;
            case 'product'://上传产品
                $this->uplodaProduct($data);
                break;
            default:
                $this->returnJson("UnParameter");
                break;
        }
    }

    /**
     * 检测产品是否存在
     * @param array $data
     * @throws \think\Exception
     */
    public function checkProduct($data = [])
    {
        $title = isset($data['Title']) ? trim($data['Title']) : '';
        if ($title == '') {
            $this->returnJson("TitleNull");
        }
        //检测违禁词
        $res = $this->checkIllegalWords($title);
        if ($res['state'] == true) {
            $this->returnJson("TitleProhibitedWords", $res['content']);
        }
        //检测产品标题是否重复
        $tmd5 = md5($title);
        $this->ProductModel = new ProductModel();
        $res = $this->ProductModel->checkProduct($tmd5, $this->username, $this->company_id);
        if ($res == true) {
            $this->returnJson("TitleRepetition");
        }
        $this->returnJson('TitleOK');
    }

    /**
     * 检测违禁词 存在true 不存在false
     * @param string $title
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function checkIllegalWords($title = '')
    {
        $data = $this->illegalWords($this->uid, $this->company_id);
        if (!checkArr($data)) {
            return $this->returnArr();
        }

        //存在违禁词，检测
        foreach ($data as $value) {
            if (strpos($title, $value['words']) !== false) {
                return $this->returnArr($value['words'], true);
            }
        }
        return $this->returnArr();
    }

    /**
     * 下载远程图片
     * @param array $data
     */
    private function uplodaImgUrl($data = [])
    {

        $Url = $data['Url'];
        $header_array = get_headers($Url, true);
        $size = $header_array['Content-Length'];//单位：字节B
        $extension = $this->extensions[$header_array['Content-Type']];
        //创建临时文件夹，下载文件
        ensure_writable_dir($this->dir . $this->temfile);
        ensure_writable_dir($this->dir . $this->path);

        $name = $this->randomkeys(8) . strtotime(date("Y-m-d H:i:s", time())) . '.' . $extension;
        $this->downloadImgUrl($Url, $this->dir . $this->temfile . $name);
        $res = $this->distinctImg($this->dir . $this->temfile . $name, $extension);
        //图片上传空间不足,子公司验证
        if ($res['res'] == true && $this->type == 2) {
            if (compareDiskSpace($this->maxhostsize, $this->currenthostsize, $size) == false) {
                $this->returnJson("UnSize");
            }
            $sql = "UPDATE ean_company SET use_capacity = (use_capacity+" . $size . ") WHERE id=" . $this->company_id;
            Db::execute($sql);
        }
        $data['module'] = $this->module;
        $data['name'] = $res['name'];
        $data['path'] = $this->path . $res['name'];
        $data['size'] = $size;
        $data['postfix'] = $extension;

        $res = $this->ResourceModel->insertResource($data, $this->uid, $this->company_id);
        if ($res == false) {
            $this->returnJson("UnImage");
        }
        $this->returnJson('ImgOK', $res);
    }

    /**
     * 图片去重
     * @param $path     临时文件夹文件绝对路径
     * @param $extension
     * @return array
     */
    private function distinctImg($path, $extension)
    {
        $md5_file = md5_file($path);
        $newpath = $this->dir . $this->path . $md5_file . '.' . $extension;
        $name = $md5_file . '.' . $extension;
        if (file_exists($newpath)) {
            //文件存在，删除临时文件，返回文件名
            unlink(iconv("utf-8", "gb2312", $path));
            return ['res' => false, 'name' => $name];
        } else {
            //文件不存在，移动临时文件文件，返回文件名
            rename($path, $newpath);
            return ['res' => true, 'name' => $name];
        }
    }

    /**
     * 下载本地图片
     * @param array $data
     */
    private function uplodaImg($data = [])
    {
        $imgfile = base64_decode($data['ImagesBase64']);

        if (empty($imgfile)) {
            $this->returnJson("UnImage");
        }
        $extension = trim($data['Extension'], ".");
        $size = strlen($imgfile);//单位：字节B
        //创建临时文件夹，下载文件
        ensure_writable_dir($this->dir . $this->temfile);
        ensure_writable_dir($this->dir . $this->path);

        $name = $this->randomkeys(8) . strtotime(date("Y-m-d H:i:s", time())) . '.' . $extension;
        file_put_contents($this->dir . $this->temfile . $name, $imgfile);
        $res = $this->distinctImg($this->dir . $this->temfile . $name, $extension);
        //图片上传空间不足,子公司验证
        if ($res['res'] == true && $this->type == 2) {
            if (compareDiskSpace($this->maxhostsize, $this->currenthostsize, $size) == false) {
                $this->returnJson("UnSize");
            }
            $sql = "UPDATE ean_company SET use_capacity = (use_capacity+" . $size . ") WHERE id=" . $this->company_id;
            Db::execute($sql);
        }

        $data['module'] = $this->module;
        $data['name'] = $res['name'];
        $data['path'] = $this->path . $res['name'];
        $data['size'] = $size;
        $data['postfix'] = $extension;

        $res = $this->ResourceModel->insertResource($data, $this->uid, $this->company_id);
        if ($res == false) {
            $this->returnJson("UnImage");
        }
        $this->returnJson('ImgOK', $res);
    }

    /**
     * 上传产品
     * @param array $data
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function uplodaProduct($data = [])
    {
        $this->ProductModel = new ProductModel();
        $this->ProductModel->checkProductTable($this->company_id);

        $Platform = $data['Platform'];
        $Category = transitionbr($data['Category']);
        $Url = transitionbr($data['Url']);
        $Proname = transitionbr($data['Proname']);
        $Price = htmlspecialchars($data['Price']);
        $Currency = $data['Currency'];
        $Shopname = transitionbr($data['Shopname']);
        $Sketch = transitionbr($data['Sketch']);//卖点
        $Description = transitionbr($data['Description']);//描述
        $keywords = isset($data['Keywords']) ? $data['Keywords'] : [];
        $keyword = checkArr($keywords) ? join("\r\n", $keywords) : $keywords;

        $Attribute = $data['Attribute'];
        $Products = $data['Products'];
        $repeat = (isset($data['ServerState']) && $data['ServerState'] != 'TitleRepetition') ? 2 : 1;
        $Images = $data['Images'];

        $content = empty($Description) ? $Sketch : $Description;
        $Sketch = empty($Sketch) ? $Description : $Sketch;

        $where['bname'] = $Category;
        $where['platform'] = $Platform;
        $where['user_name'] = $this->username;
        $caresult = DB::name('bcategory')->where($where)->find();
        if (!checkArr($caresult)) {
            $insertData['bname'] = $Category;
            $insertData['platform'] = $Platform;
            $insertData['user_name'] = $this->username;
            $insertData['truename'] = $this->truename;
            $insertData['company_id'] = $this->company_id;
            DB::name('bcategory')->insert($insertData);
        }

        if(checkArr($Attribute)){
            reset($Attribute);
            $shu = key($Attribute);
        }else{
            $Attribute = [];
            $shu = '';
        }

        if (!in_array(strtolower($shu), $this->colors) && stripos($shu, "col") === false) {//不存在颜色
            $btshuxing = 2;
        } else {
            $btshuxing = 1;
        }

        if (count($Attribute) > 1) {
            $shuxing = "ColorSize";
        } elseif (count($Attribute) == 1) {
            $shuxing = $btshuxing == 1 ? 'Color' : 'Size';
        } else {
            $shuxing = 'Size';
        }
        $guid = create_guid();
        //插入主产品
        $insertProduct['proname'] = $Proname;
        $insertProduct['tmd5'] = md5($Proname);
        $insertProduct['price'] = $Price;
        $insertProduct['saleprice'] = $Price;
        $insertProduct['skucode'] = guid();
        $insertProduct['coin'] = $Currency;
        $insertProduct['code'] = randomkeys(13);
        $insertProduct['content'] = $content;
        $insertProduct['ndate'] = date("Y-m-d", time());
        $insertProduct['bname'] = $Category;
        $insertProduct['user_name'] = $this->username;
//        $insertProduct['des'] = $Description;
        $insertProduct['keywords'] = $keyword;
        $insertProduct['weight'] = 1;
        $insertProduct['kucun'] = 50;
        $insertProduct['btname'] = $shuxing;
        $insertProduct['fromurl'] = $Url;
        $insertProduct['shopname'] = $Shopname;
        $insertProduct['platform'] = $Platform;
        $insertProduct['sketch'] = $Sketch;
        $insertProduct['guid'] = $guid;
        $insertProduct['source'] = 3;
        $insertProduct['audit'] = 1;
        $insertProduct['repeat'] = $repeat;
        $insertProduct['timestamp'] = time();
        $this->ProductModel->insertProduct($insertProduct, $this->company_id);


        //插入变体
        if (!checkArr($Products)) {
            //插入主产品图片
            $this->insertProductImg($Images, $guid);
            $this->returnJson();
        }

        //检测主产品是否有图
        $this->productImg = $this->ProductModel->checkProductImg($guid, $this->company_id);

        //变体存在上传变体信息
        $i = 0;
        foreach ($Products as $value) {
            if (!checkArr($value["Value"])) {
                continue;
            }
            $i++;
            //变体属性，颜色在前面
            if ($btshuxing == 2) {//不存在颜色
                $sx = join(',', array_reverse($value["Value"]));
            } else {
                $sx = join(',', $value["Value"]);
            }
            $serial = $i;
            //添加变体
            $insertProperty['serial'] = $serial;
            $insertProperty['cname'] = $sx;
            $insertProperty['guid'] = $guid;
            $insertProperty['price'] = $value["Price"];
            $insertProperty['saleprice'] = $value["Price"];
            $insertProperty['kucun'] = 50;
            $insertProperty['skucode'] = '';
            $this->ProductModel->insertProperty($insertProperty, $this->company_id);

            //添加变体图片
            if (isset($value["Images"]) && count($value["Images"]) > 0) {
                $t = 0;
                $insertPropertyImg = [];
                $insertProductImg = [];
                foreach ($value["Images"] as $key => $v) {
                    //主产品无图，第一个变体图填充主产品图片库
                    if ($this->productImg == false) {
                        $insertProductImg[] = ['resource_id' => $v, 'guid' => $guid, 'serial' => 0, 'px' => ($t + 1), 'updatetime' => date("Y-m-d H:i:s", time())];
                    }
                    $insertPropertyImg[] = ['resource_id' => $v, 'guid' => $guid, 'serial' => $serial, 'px' => ($t + 1), 'updatetime' => date("Y-m-d H:i:s", time())];
                    $t++;
                }
                if (checkArr($insertProductImg)) {
                    $this->ProductModel->insertImg($insertProductImg, $this->company_id, 'all');
                    $this->productImg = true;
                }
                $this->ProductModel->insertImg($insertPropertyImg, $this->company_id, 'all');
            }
        }
        //插入主产品图片
        $this->insertProductImg($Images, $guid);
        $this->returnJson();
    }

    /**
     * 插入主产品图片
     * @param array $Images
     * @param string $guid
     */
    private function insertProductImg($Images = [], $guid = '')
    {
        //插入主图
        if (checkArr($Images)) {
            $i = 0;
            foreach ($Images as $key => $value) {
                $productImg[] = ['resource_id' => $value, 'guid' => $guid, 'serial' => 0, 'px' => $i, 'updatetime' => date("Y-m-d H:i:s", time())];
                $i++;
            }
            $this->ProductModel->insertImg($productImg, $this->company_id, 'all');
        }
    }

    private function randomkeys($length)
    {
        $str = null;
        $strPol = "1234567890";//大小写字母以及数字
        $max = strlen($strPol) - 1;

        for ($i = 0; $i < $length; $i++) {
            $str .= $strPol[rand(0, $max)];
        }
        return $str;
    }

    private function downloadImgUrl($url, $path)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        $file = curl_exec($ch);
        curl_close($ch);
        $resource = fopen($path, 'a');
        fwrite($resource, $file);
        fclose($resource);
    }

    /*************************************** 一键翻译 *********************************************************/

    /**
     * 一键翻译入口
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function fanyi()
    {
        //用户登录验证
        $this->verifyLogin();

        $data = json_decode(post('data'), true);
        $version = $data['Version'];
        //版本验证
        if ($this->lastversion !== $version) {
            $this->returnJson("UnVersion");
        }
        $this->ProductModel = new ProductModel();
        $action = get('action');
        switch ($action) {
            case 'gettranslateproduce'://获取翻译的产品数据
                $this->getProduct($data);
                break;
            case 'settranslateproduce'://翻译的产品数据入库
                $this->insertProductByFanyi($data);
                break;
            default:
                $this->returnJson("UnParameter");
                break;
        }
    }

    /**
     * 获取翻译的产品数据
     * @param array $data
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function getProduct($data = [])
    {
        $res = $this->ProductModel->productInfoByFanyi($data['guid'], $data['lang'], $this->username, $this->company_id);
        if ($res['state'] == false) {
            $this->returnJson($res['content']);
        }
        $data = $res['content'];
        $data['lang'] = $this->getDictionary('lang');
        $this->returnJson('TranslateProduce', json_encode($data, JSON_FORCE_OBJECT));
    }

    /**
     * 翻译产品数据上传
     * @param array $data
     */
    private function insertProductByFanyi($data = [])
    {
//        d($data);
        if (!checkString($data['proname'])) {
            $this->returnJson("UnTranslateNoProduce");
        }
        //获取产品翻以前数据
        $productInfo = $this->ProductModel->productInfoByFanyi($data['guid'], $data['lang'], $this->username, $this->company_id, 1);
        if ($productInfo['state'] == false) {
            $this->returnJson($productInfo['content']);
        }
        $res = $this->ProductModel->insertRenderingProduct($productInfo['content'], $data, $this->username, $this->company_id);
        $this->returnJson($res['content']);
    }
}